package com.ruoyi.system.controller;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;

import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.system.domain.PropertyChange;
import com.ruoyi.system.domain.PropertyPicture;
import com.ruoyi.system.mapper.PropertyPictureMapper;
import com.ruoyi.system.mapper.PropertyShebeiMapper;
import com.ruoyi.system.service.IPropertyChangeService;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.PropertyShebei;
import com.ruoyi.system.service.IPropertyShebeiService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 实验设备Controller
 *
 * @author kite
 * @date 2025-03-24
 */
@RestController
@RequestMapping("/system/shebei")
public class PropertyShebeiController extends BaseController {
    @Autowired
    private IPropertyShebeiService propertyShebeiService;
    @Autowired
    private PropertyPictureMapper propertyPictureMapper;
    @Autowired
    private IPropertyChangeService propertyChangeService;
    @Autowired
    private PropertyShebeiMapper propertyShebeiMapper;

    /**
     * 查询实验设备列表
     */
    @PreAuthorize("@ss.hasPermi('system:shebei:list')")
    @GetMapping("/list")
    public TableDataInfo list(PropertyShebei propertyShebei) {
        startPage();
        SysUser user = getLoginSysUser();

        Optional<SysRole> first = user.getRoles().stream().filter(role -> "common".equals(role.getRoleKey())).findFirst();
        if (first.isPresent()) {
            propertyShebei.setCreateBy(getUsername());
        }
        List<PropertyShebei> list = propertyShebeiService.selectPropertyShebeiList(propertyShebei);
        return getDataTable(list);
    }

    /**
     * 导出实验设备列表
     */
    @PreAuthorize("@ss.hasPermi('system:shebei:export')")
    @Log(title = "实验设备", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, PropertyShebei propertyShebei) {
        List<PropertyShebei> list = propertyShebeiMapper.selectPropertyShebeiList(propertyShebei);
        ExcelUtil<PropertyShebei> util = new ExcelUtil<PropertyShebei>(PropertyShebei.class);
        util.exportExcel(response, list, "实验设备数据");
    }

    /**
     * 获取实验设备详细信息
     */

    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(propertyShebeiService.selectPropertyShebeiById(id));
    }

    /**
     * 新增实验设备
     */
    @PreAuthorize("@ss.hasPermi('system:shebei:add')")
    @Log(title = "实验设备", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody PropertyShebei propertyShebei) {
        //设备数据中的修订人永远是该系统登入人
        SysUser user = getLoginSysUser();
        propertyShebei.setRevisedPeople(user.getUserName());//工号
        propertyShebei.setBackupFields9(user.getNickName());//姓名
        try {
            return toAjax(propertyShebeiService.insertPropertyShebei(propertyShebei));
        } catch (ServiceException e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 修改实验设备
     */
//    @PreAuthorize("@ss.hasPermi('system:shebei:edit')")
    @Log(title = "实验设备", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody PropertyShebei propertyShebei) {
        SysUser user = getLoginSysUser();
        propertyShebei.setRevisedPeople(user.getUserName());//工号
        propertyShebei.setBackupFields9(user.getNickName());//姓名
        return toAjax(propertyShebeiService.updatePropertyShebei(propertyShebei));
    }

    /**
     * 删除实验设备
     */
    @PreAuthorize("@ss.hasPermi('system:shebei:remove')")
    @Log(title = "实验设备", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(propertyShebeiService.deletePropertyShebeiByIds(ids));
    }

    @PreAuthorize("@ss.hasPermi('system:shebei:add')")
    @Log(title = "设备资产导入", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        try{
            InputStream inputStream = file.getInputStream();
            Workbook workbook = WorkbookFactory.create(inputStream);
            Sheet sheet = workbook.getSheetAt(0); // 获取第一个工作表
            int rowCount = sheet.getPhysicalNumberOfRows();

            // 减去表头行
            int dataRowCount = rowCount - 1;

            if (dataRowCount > 10000) {
                throw new ServiceException("导入失败，Excel数据行数不能超过100行，当前行数: " + dataRowCount);
            }
        } catch (IOException e) {
            return AjaxResult.error(e.getMessage());
        }
        propertyShebeiService.importData(file);
        return success("导入成功");
    }

    /**
     * 下载导入模板
     */
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<PropertyShebei> util = new ExcelUtil<>(PropertyShebei.class);
        util.importTemplateExcel(response, "设备资产数据");
    }

    @PostMapping("/getBatchEditImportTemplate")
    public void getBatchEditImportTemplate(HttpServletResponse response) {
        ExcelUtil<PropertyShebei> util =
                new ExcelUtil<>(PropertyShebei.class);
        util.importTemplateExcel(response, "批量修改数据");
    }

    @PreAuthorize("@ss.hasPermi('system:shebei:edit')")
    @Log(title = "批量修改设备资产", businessType = BusinessType.IMPORT)
    @PostMapping("/batchUpload")
    @RepeatSubmit(interval = 1000, message = "请求过于频繁")
    public AjaxResult batchEdit(MultipartFile file, boolean updateSupport) {
        try{
            InputStream inputStream = file.getInputStream();
            Workbook workbook = WorkbookFactory.create(inputStream);
            Sheet sheet = workbook.getSheetAt(0); // 获取第一个工作表
            int rowCount = sheet.getPhysicalNumberOfRows();

            // 减去表头行
            int dataRowCount = rowCount - 1;

            if (dataRowCount > 10000) {
                throw new ServiceException("导入失败，Excel数据行数不能超过100行，当前行数: " + dataRowCount);
            }
        } catch (IOException e) {
            return AjaxResult.error(e.getMessage());
        }
        propertyShebeiService.batchEdit(file);
        return success("导入成功");
    }

    @PostMapping("/uploadPropertyPicture")
    @Transactional
    public AjaxResult uploadPropertyPicture(MultipartFile file, String propertyName) throws Exception {

        // 上传文件路径
        String filePath = RuoYiConfig.getUploadPath();
        // 上传并返回新文件名称
        String fileName = FileUploadUtils.upload(filePath, file);
        PropertyPicture propertyPicture = new PropertyPicture();
        propertyPicture.setPropertyName(propertyName);
        propertyPicture.setPropertyType("1");
        propertyPicture.setPictureUrl(fileName);
        propertyPicture.setUpload(SecurityUtils.getUsername());
        propertyPicture.setUploadDt(new Date());
        propertyPictureMapper.deleteByNameAndType(propertyName, "1");
        propertyPictureMapper.insertPropertyPicture(propertyPicture);
        return success("上传成功");
    }

    @PreAuthorize("@ss.hasPermi('system:shebei:list')")
    @GetMapping("/listByChange")
    public List<Map<String, Object>> listByChange(PropertyChange propertyChange) {
        return propertyChangeService.selectByNumberAndType(propertyChange.getInstrumentNumber(), "设备资产");
    }

    /**
     * 获取当前登录用户信息
     *
     * @return 登录用户信息
     */
    @NotNull
    private SysUser getLoginSysUser() {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (loginUser == null) {
            throw new RuntimeException("请先登录");
        }
        SysUser user = loginUser.getUser();
        if (user == null) {
            throw new RuntimeException("当前用户信息为空");
        }
        return user;
    }
}
